package net.huashitong.supervision.gongjian.web;

import com.sirdc.modules.core.web.JsonBaseController;
import com.sirdc.modules.core.web.model.JqGrid;
import com.sirdc.modules.core.web.model.Message;
import com.sirdc.modules.sys.service.RedisService;
import com.sirdc.modules.sys.util.SysUserUtils;
import com.sirdc.modules.utils.ObjectUtils;
import com.sirdc.modules.utils.StringUtils;
import net.huashitong.supervision.gongjian.dto.FeedBackDTO;
import net.huashitong.supervision.gongjian.dto.GjProjectDTO;
import net.huashitong.supervision.gongjian.entity.ProjectFeedBackEntity;
import net.huashitong.supervision.gongjian.entity.ProjectTaskEntity;
import net.huashitong.supervision.gongjian.entity.project.ZhengQianEntity;
import net.huashitong.supervision.gongjian.filter.ProjectFeedBackFilter;
import net.huashitong.supervision.gongjian.filter.ProjectTaskFilter;
import net.huashitong.supervision.gongjian.filter.ZhengQianFilter;
import net.huashitong.supervision.gongjian.service.GjDeptProjectService;
import net.huashitong.supervision.gongjian.service.ProjectFeedBackService;
import net.huashitong.supervision.gongjian.service.ProjectTaskService;
import net.huashitong.supervision.gongjian.service.project.ZhengQianService;
import net.huashitong.util.DateUtil;
import org.apache.http.entity.FileEntity;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;

@Controller
@RequestMapping("/sys/gongjian/")
public class ZhengdiJiaoqianCtrl extends JsonBaseController {
    @Autowired
    private ZhengQianService zhengQianService;
    @Autowired
    private ProjectTaskService taskService;
    @Autowired
    private GjDeptProjectService deptProjectService;
    @Autowired
    private ProjectFeedBackService feedBackService;
    @Autowired
    private RedisService redisService;


    @Override
    protected String getView(String s) {
        return "/modules/task/gjtask/"+s;
    }


//    kaigonglist,zhengqianlist,jungonglist,zaijianlist,zhaoshanglist
    @RequiresPermissions(value = {"sys:gongjian:kaigonglist",
            "sys:gongjian:zhengqianlist",
            "sys:gongjian:jungonglist",
            "sys:gongjian:zaijianlist",
            "sys:gongjian:zhaoshanglist"
    },

            logical = Logical.OR)
    @RequestMapping(method = RequestMethod.GET)
    public String initPage() {
        return getView("query");
    }

    /**
     * 返回列表
     * @param filter
     * @return
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST)
    public JqGrid queryFilter(ZhengQianFilter filter){
        String deptId = SysUserUtils.getDeptId();
        filter.setDeptId(deptId);
        filter.setDeptType(2);
        List<ZhengQianEntity> list = zhengQianService.getLists(filter);


        List<FeedBackDTO> dataList = new ArrayList<>();
        for (ZhengQianEntity item : list) {
            FeedBackDTO dto  = new FeedBackDTO();
            BeanUtils.copyProperties(item,dto);
            dto.setProjId(item.getSysId());
            dto.setLevel(0);
            dto.setIsLeaf(true);
            dto.setExpanded(true);
            dto.setSysId(item.getSysId());
            dto.setProjectId(item.getSysId());
            List<ProjectFeedBackEntity> backList = feedBackService.getCurrentFeedBackList(item.getSysId(), 1, 1,SysUserUtils.getusername());
            if(!CollectionUtils.isEmpty(backList)){
//                    dto.setSysId(backList.get(0).getSysId());
                    dto.setProjId(item.getSysId());
                    dto.setProjectId(item.getSysId());
                    dto.setFeedbackId(backList.get(0).getSysId());
                    dto.setBackRemark(backList.get(0).getRemarks());
                    dto.setCurrentMianji(backList.get(0).getCurrentMianji());
                    dto.setFinishMianji(backList.get(0).getFinishMianji());
                    dto.setCurrentChaiqian(backList.get(0).getFinishChaiqian());
                    dto.setFinishChaiqian(backList.get(0).getFinishChaiqian());
                    dto.setCurrentZhengqianhu(backList.get(0).getCurrentZhengqianhu());
                    dto.setFinishZhengqianhu(backList.get(0).getFinishZhengqianhu());
                    dto.setReachoals(backList.get(0).getReachoals());
                    dto.setXingxiang(backList.get(0).getXingxiang());
                    int zhengdiAudit = backList.get(0).getZhengdiAudit();
                    dto.setCreateName(backList.get(0).getCreateName());
                    dto.setCreateDate(backList.get(0).getCreateDate()+" "+backList.get(0).getCreateTime());
                    String a1 = auditName(zhengdiAudit);
                    String a2 = auditName(backList.get(0).getChaiqianAudit());
                    dto.setAuditInfo("征地审核："+a1+"\n"+"拆迁审核："+a2);
                    dto.setCreateDate(backList.get(0).getCreateDate()+" "+backList.get(0).getCreateTime());

                dataList.add(dto);

            }else {
                dataList.add(dto);
            }
        }


        return coverJqGrid(filter,dataList);
    }

    /**
     * 打开反馈页面
     * @param model
     * @param id
     * @return
     */
    @RequestMapping(value = "/edit/{id}", method = RequestMethod.GET)
    public String showEditView(Model model, @PathVariable String id) {
        //根据自己的过滤规则过滤部门，将来可以考虑是否要修改成下拉树
       /* List<SysDept> depts = sysDeptService.query();
        SysUserDataBean datebean = sysUserService.getUserDataBeanById(id);
        model.addAttribute("datebean", datebean);
        model.addAttribute("depts", depts);*/
        System.out.println(id); //taskId
        model.addAttribute("projectDetail",new ZhengQianEntity());
        model.addAttribute("taskId",id);

        return getView("feedbackForm");
    }

    /**
     * 反馈任务

     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/feedback", method = RequestMethod.POST)
    public Message feedBackTask(@ModelAttribute ProjectFeedBackFilter feedBackFilter) {
        String taskId = feedBackFilter.getTaskId();//反馈Id
        if(StringUtils.isBlank(taskId))
        {
            return coverMessage("500", "参数错误");
        }

        ProjectFeedBackEntity feedback = new ProjectFeedBackEntity();

        int i = feedBackService.saveFeedback(feedBackFilter);
        if(i==1){

            return coverMessage("200","反馈成功");
        }else  if(2==i){

            return  coverMessage("500","反馈失败,登陆超时");
        }else {

            return  coverMessage("500","反馈失败,审核通过的无法再次修改修改");
        }


//        List<ProjectFeedBackEntity> list = feedBackService.getList(sysId);

    }




    /**
     * 打开详情页
     * feedbackForm  乡镇反馈
     *
     */
    @RequestMapping(value="/detail/{id}",method = RequestMethod.GET)
    public String projectDetail(@PathVariable String id, Model model) {
        System.out.println(id);

        ZhengQianEntity zhengQianEntity = zhengQianService.getById(id);

        model.addAttribute("projectDetail",zhengQianEntity);


        model.addAttribute("projectId",zhengQianEntity.getSysId());
        //查询项目的 deptType  配合单位 1 和 责任单位2
//                projectType 1 征迁交地   2  开工提速 3 在建提速，4 竣工投产 5  招商专项行动；
        List<GjProjectDTO> peiheList = deptProjectService.getProjectDeptList(zhengQianEntity.getSysId(), 1,1);
        String peihes ="";
        for (GjProjectDTO item : peiheList) {
            peihes=item.getDeptName()+"、"+peihes;

        }
        List<GjProjectDTO> zerenList = deptProjectService.getProjectDeptList(zhengQianEntity.getSysId(), 2,1);
        String zerens ="";
        for (GjProjectDTO item : zerenList) {
            zerens=item.getDeptName()+"、"+zerens;

        }
        model.addAttribute("peihe",peihes);
        model.addAttribute("zeren",zerens);


        return  getView("gongjian_detail");
    }

    /**
       2级页面
       管理端查询每个月的任务和反馈
     */
    @ResponseBody
    @RequestMapping(value = "/projectTasks",method = RequestMethod.POST)
    public JqGrid getProjectTaskList(ProjectTaskFilter filter){

        String projectId = filter.getProjectId();//征迁项目id

//        获取每个月所有任务，
        List<ProjectFeedBackFilter> list=null;
        filter.setValid(2);//2 查看所有状态 查看有效和无效的任务 0 无效，1 有效
        list = taskService.getListAll(filter,filter.getProjectType());

        return coverJqGrid(filter, list);
    }

    /**
     *
     * 2级页面
     * 责任单位只看自己任务和反馈
     * @param filter
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/projectTasks/own",method = RequestMethod.POST)
    public JqGrid getProjectTaskListOwn(ProjectTaskFilter filter){

        String projectId = filter.getProjectId();//征迁项目id

//        获取每个月所有任务，
        List<ProjectFeedBackFilter> list=null;
        filter.setValid(2);//2 查看所有状态 查看有效和无效的任务 0 无效，1 有效
        list = taskService.getListByOwn(filter,filter.getProjectType());

        return coverJqGrid(filter, list);
    }



    /**
     * 管理端
     * /sys/gongjian/zhengqian/manage
     */

    @RequestMapping(value = "/zhengqian/manage",method = RequestMethod.GET)
    public String initManagePage() {
        return getView("zhengqian/query_manage");
    }

    @ResponseBody
    @RequestMapping(value = "/zhengqian/manage",method = RequestMethod.POST)
    public JqGrid zhengqianManage(ZhengQianFilter filter){

        List<ZhengQianEntity> list = zhengQianService.getList(filter);

        List<FeedBackDTO> dataList = new ArrayList<>();
        for (ZhengQianEntity item : list) {
            FeedBackDTO dto  = new FeedBackDTO();
            BeanUtils.copyProperties(item,dto);
            dto.setProjId(item.getSysId());
            dto.setLevel(0);
            dto.setIsLeaf(true);
            dto.setExpanded(true);
            dto.setSysId(item.getSysId());
            dto.setProjectId(item.getSysId());

            List<ProjectFeedBackEntity> backList = feedBackService.getCurrentFeedBackList(item.getSysId(), 1, 1,null);
            if(!CollectionUtils.isEmpty(backList)){
//                dto.setIsLeaf(false);
                if(backList.size()>1){
                    dto.setIsLeaf(false);
                    dataList.add(dto);
                    int index=1;
                    for (ProjectFeedBackEntity feedback : backList) {

                        FeedBackDTO itemDto  = new FeedBackDTO();

                        itemDto.setCurrentBack(item.getCurrentBack());
                        itemDto.setProjectName("      "+"("+index+")"+item.getProjectName());
                        itemDto.setLevel(1);
                        itemDto.setIsLeaf(true);
                        itemDto.setParent(item.getSysId());
                        itemDto.setExpanded(true);
                        itemDto.setSysId(feedback.getSysId());
                        itemDto.setProjId(item.getSysId());
                        itemDto.setProjectId(item.getSysId());
                        itemDto.setFeedbackId(feedback.getSysId());
                        itemDto.setBackRemark(feedback.getRemarks());
                        itemDto.setReachoals(feedback.getReachoals());
                        itemDto.setXingxiang(feedback.getXingxiang());
                        itemDto.setCurrentMianji(feedback.getCurrentMianji());
                        itemDto.setFinishMianji(feedback.getFinishMianji());
                        itemDto.setCurrentChaiqian(feedback.getFinishChaiqian());
                        itemDto.setFinishChaiqian(feedback.getFinishChaiqian());
                        itemDto.setCurrentZhengqianhu(feedback.getCurrentZhengqianhu());
                        itemDto.setFinishZhengqianhu(feedback.getFinishZhengqianhu());
                        int zhengdiAudit = feedback.getZhengdiAudit();
                        itemDto.setCreateName(feedback.getCreateName());
                        itemDto.setCreateDate(feedback.getCreateDate()+" "+feedback.getCreateTime());
                        String a1 = auditName(zhengdiAudit);
                        String a2 = auditName(feedback.getChaiqianAudit());
                        itemDto.setAuditInfo("征地审核："+a1+"\n"+"拆迁审核："+a2);
                        dataList.add(itemDto);
                        index=index+1;
                    }
                }else {
                    dto.setSysId(backList.get(0).getSysId());
                    dto.setProjId(item.getSysId());
                    dto.setProjectId(item.getSysId());
                    dto.setFeedbackId(backList.get(0).getSysId());
                    dto.setBackRemark(backList.get(0).getRemarks());
                    dto.setCurrentMianji(backList.get(0).getCurrentMianji());
                    dto.setFinishMianji(backList.get(0).getFinishMianji());
                    dto.setCurrentChaiqian(backList.get(0).getFinishChaiqian());
                    dto.setFinishChaiqian(backList.get(0).getFinishChaiqian());
                    dto.setCurrentZhengqianhu(backList.get(0).getCurrentZhengqianhu());
                    dto.setFinishZhengqianhu(backList.get(0).getFinishZhengqianhu());
                    dto.setReachoals(backList.get(0).getReachoals());
                    dto.setXingxiang(backList.get(0).getXingxiang());
                    int zhengdiAudit = backList.get(0).getZhengdiAudit();
                    dto.setCreateName(backList.get(0).getCreateName());
                    dto.setCreateDate(backList.get(0).getCreateDate()+" "+backList.get(0).getCreateTime());
                    String a1 = auditName(zhengdiAudit);
                    String a2 = auditName(backList.get(0).getChaiqianAudit());
                    dto.setAuditInfo("征地审核："+a1+"\n"+"拆迁审核："+a2);
                    dataList.add(dto);
                }


            }else {
                dataList.add(dto);
            }
        }

        return coverJqGrid(filter,dataList);
    }

    private String auditName(int audit)
    {
        switch (audit)
        {
            case 0:

                return "未审核";

            case 1:
                return "已审核";

            case 2:
                return "审核不通过";
        }
        return "";
    }



    @RequiresPermissions(value = {"sys:gongjian:zhengqian:manage:auditzhengqian","sys:gongjian:zhengqian:manage:auditcaiqian"},logical = Logical.OR)
    @RequestMapping(value="/zhengqian/manage/detail/{id}",method = RequestMethod.GET)
    public String showManage(@PathVariable String id, Model model) {
        System.out.println(id);

        ZhengQianEntity zhengQianEntity = zhengQianService.getById(id);

        model.addAttribute("projectDetail",zhengQianEntity);


        model.addAttribute("projectId",zhengQianEntity.getSysId());
        //查询项目的 deptType  配合单位 1 和 责任单位2
//                projectType 1 征迁交地   2  开工提速 3 在建提速，4 竣工投产 5  招商专项行动；
        List<GjProjectDTO> peiheList = deptProjectService.getProjectDeptList(zhengQianEntity.getSysId(), 1,1);
        String peihes ="";
        for (GjProjectDTO item : peiheList) {
            peihes=item.getDeptName()+"、"+peihes;

        }
        List<GjProjectDTO> zerenList = deptProjectService.getProjectDeptList(zhengQianEntity.getSysId(), 2,1);
        String zerens ="";
        for (GjProjectDTO item : zerenList) {
            zerens=item.getDeptName()+"、"+zerens;

        }
        model.addAttribute("peihe",peihes);
        model.addAttribute("zeren",zerens);


        return  getView("/zhengqian/zhengqian_manage_detail");
    }


    @ResponseBody
    @RequestMapping(value = "/auditFeedback/{id}")
    public Message delete(@PathVariable List<String> id,@ModelAttribute ProjectFeedBackFilter feedBackFilter) {

        int projectType = feedBackFilter.getProjectType();
        int audit =feedBackFilter.getAudit();
        for (String s : id) {
            System.out.println(s);

            ProjectFeedBackEntity feedback = feedBackService.getById(s);

            switch (projectType)
            {
                case 1:
                    int auditType = feedBackFilter.getAuditType();
                    if(1==auditType)
                    {
                        //征地
                        feedback.setZhengdiAudit(audit);

                    } else if (2 == auditType) {
                        //拆迁
                        feedback.setChaiqianAudit(audit);
                    }

                    break;

                default:
                    feedback.setAudit(audit);
                    break;
            }
            feedback.setAuditer(SysUserUtils.getusername());
            feedback.setAuditDate(DateUtil.getCurrentDate()+" "+DateUtil.getCurrentTime());
            feedBackService.update(feedback);

        }

        System.out.println(feedBackFilter.getProjectType());
        System.out.println(feedBackFilter.getAudit());


        return coverMessage("200");
    }


}
